package com.example.exceldemo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import java.io.File;

/**
 * 文件路径配置类
 */
@Slf4j
@Configuration
public class PathConfig {
    
    private static final String OS_NAME = System.getProperty("os.name").toLowerCase();
    
    private static boolean isWindows() {
        return OS_NAME.contains("win");
    }
    
    private static boolean isLinux() {
        return OS_NAME.contains("linux") || OS_NAME.contains("unix");
    }
    
    @Autowired
    private AppConfig appConfig;
    
    private String uploadDir;
    private String outputDir;
    private String logDir;
    
    @PostConstruct
    public void init() {
        try {
            // 根据操作系统类型选择存储路径
            if (isLinux()) {
                appConfig.getUpload().setDir("/upload");
                appConfig.getOutput().setDir("/docGen");
                this.logDir = "/home/root/docGen/logs";
            } else {
                this.logDir = System.getProperty("user.home") + "/logs/docgen";
            }
            
            // 确保上传和输出目录对象已初始化
            if (appConfig.getUpload() == null) {
                appConfig.setUpload(new AppConfig.Upload());
                appConfig.getUpload().setDir(System.getProperty("user.home") + "/uploads/docgen");
            }
            
            if (appConfig.getOutput() == null) {
                appConfig.setOutput(new AppConfig.Output());
                appConfig.getOutput().setDir(System.getProperty("user.home") + "/docoutput");
            }
            
            // 保存目录路径供后续使用
            this.uploadDir = appConfig.getUpload().getDir();
            this.outputDir = appConfig.getOutput().getDir();
            
            // 初始化路径目录
            initDirectories();
            
            log.info("系统类型: {}, 上传目录: {}, 输出目录: {}, 日志目录: {}", 
                    OS_NAME, uploadDir, outputDir, logDir);
        } catch (Exception e) {
            log.error("初始化路径配置时出错", e);
            // 设置默认值以避免后续NPE
            this.uploadDir = System.getProperty("user.home") + "/uploads/docgen";
            this.outputDir = System.getProperty("user.home") + "/docoutput";
            this.logDir = System.getProperty("user.home") + "/logs/docgen";
            
            // 确保默认目录存在
            ensureDirectoryExists(uploadDir);
            ensureDirectoryExists(outputDir);
            ensureDirectoryExists(logDir);
        }
    }
    
    @EventListener(ContextRefreshedEvent.class)
    public void checkDirectoriesAfterStartup() {
        checkDirectoryPermissions(uploadDir);
        checkDirectoryPermissions(outputDir);
        checkDirectoryPermissions(logDir);
        
        if (isLinux()) {
            // 在Linux系统上设置目录权限
            try {
                log.info("在Linux系统上设置目录权限");
                executeCommand("chmod -R 755 " + uploadDir);
                executeCommand("chmod -R 755 " + outputDir);
                executeCommand("chmod -R 755 " + logDir);
            } catch (Exception e) {
                log.error("设置目录权限时出错", e);
            }
        }
    }
    
    /**
     * 执行系统命令
     */
    private void executeCommand(String command) {
        try {
            log.info("执行命令: {}", command);
            Process process = Runtime.getRuntime().exec(command);
            int exitCode = process.waitFor();
            log.info("命令执行完成，退出码: {}", exitCode);
        } catch (Exception e) {
            log.error("执行命令时出错: {}", command, e);
            throw new RuntimeException("执行命令失败: " + command, e);
        }
    }
    
    private void checkDirectoryPermissions(String dirPath) {
        File dir = new File(dirPath);
        if (!dir.exists()) {
            boolean created = dir.mkdirs();
            if (!created) {
                log.error("无法创建目录: {}", dirPath);
            }
            return;
        }
        
        if (!dir.canRead() || !dir.canWrite()) {
            log.error("目录权限不足: {}", dirPath);
        }
    }
    
    private void initDirectories() {
        ensureDirectoryExists(uploadDir);
        ensureDirectoryExists(outputDir);
        ensureDirectoryExists(logDir);
    }
    
    private void ensureDirectoryExists(String dirPath) {
        if (dirPath == null) {
            log.error("目录路径为null");
            return;
        }
        
        File dir = new File(dirPath);
        if (!dir.exists()) {
            boolean created = dir.mkdirs();
            if (!created) {
                log.warn("无法创建目录: {}", dirPath);
            } else {
                log.info("成功创建目录: {}", dirPath);
            }
        }
    }
} 